/******** Misc ***********/

function checkOpenFrom(){
	//检查result页面是从my。htm 打开还是直接打开
	if(window.top == window){
		return false;
	}else {
		return true;
	}
}


var pieChartObj, barChartObj;

/********* Main Area *************/
function hideMainArea(){
	var el = document.getElementById('poll-result');
	el.classList.add('hidden');
}
function showMainArea(){
	var el = document.getElementById('poll-result');
	el.classList.remove('hidden');
}


/********* Options Operator **********/

var rawData={};
function addOption(data){
	var opls = document.getElementById('option-list');
	var moel = document.getElementById('model').cloneNode(true);
	var frontWidth = 12;//need to calculate
	moel.addEventListener('onclick',function(){showRecords(data['item_id']);})
	moel.getElementsByClassName('name')[0].innerHTML = data.name;
	moel.getElementsByClassName('fa')[0].className = data.checked?'fa fa-check-square':'fa fa-square';
	moel.getElementsByClassName('front')[0].style.width = frontWidth+'%';
	moel.getElementsByClassName('number')[0].innerHTML = data.number;
	//moel.getElementsByClassName('name')[0].innerHTML = data.name;
	opls.appendChild(moel);
}

function setData(data){
	var opls = document.getElementById('option-list');
	opls.innerHTML = '';
	
	if(!data['is_viewable']){
		document.getElementById('poll-title').innerHTML = '投票结果不公开';
		//document.getElementById('chart-section').style.display = 'none';
		showMsgBox();
		hideMainArea();
		return false;
	}
	//Cope Raw Data
	data['is_over'] = data.items[0]['is_over'];

	data.totalNum = 0;

	for(var i=0;i<data.items.length;i++){
		data.totalNum += parseFloat(data.items[i]['total_value']);
	}
	data.totalNum = rounder(data.totalNum);
	
	//Add Result Bar
	//var sortedArray = .slice(0);
	sortedArray = data.items.sort(function(a,b){
		return b['total_value'] - a['total_value'];
	});
	for(var i=0;i<sortedArray.length;i++){
		var opdata = sortedArray[i];
		var moel = document.getElementById('model').cloneNode(true);
		//var frontWidth = ;//need to calculate
		moel.id = opdata['item_id'];
		moel.getElementsByClassName('name')[0].innerHTML = opdata['content'];
		moel.getElementsByClassName('checkbox')[0].className = opdata['user_value']?'checkbox checked':'checkbox';
		moel.getElementsByClassName('front')[0].style.width = (opdata['total_value']/data.totalNum*100)+'%';
		moel.getElementsByClassName('number')[0].innerHTML = rounder(opdata['total_value']);
		moel.addEventListener('click',(function(i){return function(){showRecords(i);}})(opdata['item_id']));
		//moel.getElementsByClassName('name')[0].innerHTML = data.name;
		opls.appendChild(moel);
	}

	document.getElementById('total-number').innerHTML = data.totalNum;
	var pollTypeMap = {'0':'单选','1':'多选','2':'权重选'};
	document.getElementById('poll-type').innerHTML = pollTypeMap[data['room_type']];
	document.getElementById('poll-status').className = data['is_over']?'poll-status dark':'poll-status light';
	document.getElementById('poll-title').innerHTML = data['theme'];
	document.getElementById('poll-deadline').innerHTML = getTime(data['end_time']);

	// 根据选项数更改图表显示
	var cobj = document.getElementById('chart-section');
	if(data.items.length <= 8){
		cobj.classList.remove('hidden');
		cobj.classList.remove('only-canvas');
	}else if(data.items.length <= 13){
		cobj.classList.add('only-canvas');
		cobj.classList.remove('hidden');
	}else {
		cobj.classList.add('hidden');
		cobj.classList.remove('only-canvas');
	}

	createChart(data.items);
	showMainArea();
}

function fetchData(){
	var para = getAnchor().split('@');
	var url = API_URL+'?type=2&room_id='+para[0]+'';
	getJSON(url,function(data,status){
		loadingBox.hide();
		setData(data);
	});
	loadingBox.show({shadow:false});
}



/********   Chart   ********/

var chart_color_index = -1;
function createChart(rawData){
	var para = {'legendPosition':''}
	//resize chart area
	var barArea = document.getElementById("chart-canvas-bar");
	var pieArea = document.getElementById("chart-canvas-pie");
	barArea.style.height = Math.min(barArea.offsetWidth*3/4,200);
	pieArea.style.height = Math.min(pieArea.offsetWidth*3/4,200);
	if(barArea.offsetWidth<=100){
		para['legendPosition'] = 'bottom';
	}else{
		para['legendPosition'] = 'left';
	}

	var newData = [];
	for(var i=0;i<rawData.length;i++){
		newData.push({'label':rawData[i].content,'data':[rounder(rawData[i]['total_value'])],'backgroundColor':getColorLoop(i),});
	}

	//Add Extra Legend
	//var legendListb = document.getElementById('chart-legend-bar');
	var legendListp = document.getElementById('chart-legend');
	//legendListb.innerHTML = '';
	legendListp.innerHTML = '';
	for(var i=0; i<newData.length; i++){
		var nod = document.createElement('li');
		nod.innerHTML = '<span style="background:' +newData[i]['backgroundColor']+ ';">&nbsp;</span>'+ newData[i]['label']+'';
		legendListp.appendChild(nod);
		//legendListb.appendChild(nod.cloneNode(true));
	}

	//Draw Chart Picture - bar
	var ctx = document.getElementById('chart-canvas-bar');
	var myChart = new Chart(ctx, {
		type: 'bar',
		data: {
			datasets: newData,
		},
		options: {
			padding:0,
			maintainAspectRatio:true,
			legend: {
				display: false,
				position:para['legendPosition'],
				labels:{'boxWidth':12,usePointStyle:false,'fontSize':12,'padding':12},
				'fullWidth':false,
			},
			scales: {
				xAxes:[{
					categoryPercentage: 1.0,
					barPercentage: 0.8,
				}],
				yAxes: [{
					gridLines:{'display':false},
					tickMarkLength:6,
					ticks:{
						beginAtZero:true,
						min:0,
						fontSize:10,
						padding:3,
					},
				}]
			}
		},
	});
	var pieData ={'labels':[],'datasets':[{'data':[],'backgroundColor':[]}]};
	for(var i=0;i<rawData.length;i++){
		pieData.labels.push(rawData[i].content);
		pieData.datasets[0].data.push(rounder(rawData[i]['total_value']));
		pieData.datasets[0].backgroundColor.push(getColorLoop(i));
	}

	//Draw Chart Picture - pie
	var ctx = document.getElementById('chart-canvas-pie');
	var myChart2 = new Chart(ctx, {
		type: 'pie',
		data: pieData,
		options: {
			maintainAspectRatio:true,
			legend: {
				display: false,
				position:para['legendPosition'],
				labels:{'boxWidth':12,usePointStyle:false,'fontSize':12,'padding':12},
				'fullWidth':false,
			},
		}
	});

	//switch to pie 
	toggleChartType('pie');
	pieChartObj = myChart2;
	barChartObj = myChart;
}

function getColorLoop(i){
	var colorList = ['#F9CC8A','#CBE099','#83CBC8','#F19A76','#FEF69A','#8C97CA'];
	return colorList[i%colorList.length];
}


function toggleChartType(type){
	document.getElementById('chart-section').dataset.chartType = type;
}

/*********** Record *************/

function addRecord(data){
	var pollList = document.getElementById('record-ul');
	var moel = document.getElementById('model-record').cloneNode(true);
	moel.id = '';

	moel.getElementsByClassName('nickname')[0].innerHTML = data['nickname'];
	moel.getElementsByClassName('time')[0].innerHTML = getTime(data['vote_time']);
	moel.getElementsByClassName('will-num')[0].innerHTML = data['poll_persentage'];
	moel.getElementsByClassName('avatar')[0].src = data['voter_img'] || 'img/default-avatar.png';
	
	pollList.appendChild(moel);
}

function setRecords(data){
	//Clear old data
	var ullist = document.getElementById('record-ul');
	var licol =  ullist.childNodes;
	ullist.innerHTML = '';
	
	//update common data
	var pel = document.getElementById('poll-record');
	pel.getElementsByClassName('option-name')[0].innerHTML = data['item']['content'];
	pel.getElementsByClassName('total-number')[0].innerHTML = data.data.length;
	
	//add list
	var itemCount = 0;
	for(var i=0; i<data.data.length; i++){
		if(data.data[i]['poll_persentage'] > 0){
			addRecord(data.data[i]);
			itemCount++;
		}
	}
	pel.getElementsByClassName('total-number')[0].innerHTML = itemCount;
}

function showRecords(opid){
	//alert('showing::::'+opid);$('#').show();
	var url = API_URL + '?type=5&item_id=' + opid;
	getJSON(url,function(data){
		if(data.error){
			showmsg(data.error);
		}else{
			setRecords(data);
			loadingBox.hide();
			document.getElementById('poll-record').className = '';
		}
	});
	loadingBox.show({shadow:true});
	disableBodyScroll();
}

function closeRecords(){
	document.getElementById('poll-record').className = 'hidden';
	//Clear old data
	setRecords({"item":{"item_id":"","content":"","room_id":"20"},"data":[]});
	enableBodyScroll();
}



function createChart2(rawData){
	var para = {'legendPosition':''}
	//resize chart area
	var barArea = document.getElementById("chart-area-bar");
	var pieArea = document.getElementById("chart-area-pie");
	barArea.style.height = Math.min(barArea.offsetWidth*3/4,200);
	pieArea.style.height = Math.min(pieArea.offsetWidth*3/4,200);
	if(barArea.offsetWidth<=400){
		para['legendPosition'] = 'bottom';
	}else{
		para['legendPosition'] = 'left';
	}
		

	//generate data for chart maker
	var newData=[];
	for(var i=0;i<rawData.length;i++){
		newData.push({'name':rawData[i].content,'number':rounder(rawData[i]['total_value']),'color':getColorLoop(i)});
	}

	var pieChart =  new dhtmlXChart({
		view:"pie",
		container:"chart-area-pie",
		value:"#number#",
		label:'',
		color:'#color#',
		legend:{
			width: 100,
			align: '#left#',
			valign: "middle",
			template: "#name#",
			layout:"y",
			marker:{
				type: "square",
				width: 13,
				height:13,
				radius:0,
			},
		},
		sort:{
			by:"#number#",
			dir:"dsc",
			as:"int"
		},
		tooltip:"#number#",
		pieInnerText:function(obj){return Math.round(obj.number/pieChart.sum('#number#')*100) +"%   ";},
		shadow:false,
	});
	pieChart.parse(newData,"json");


	var barChart =  new dhtmlXChart({
		view:"bar",
		container:"chart-area-bar",
		value:"#number#",
		//label:function(obj){return (Math.round(obj.number/pieChart.sum('#number#')*100)) +"%"},
		label:'#number#',
		color:'#color#',
		legend:{
			width: 100,
			align: '#left#',
			valign: "middle",
			template: "#name#",
			layout:"y",
			marker:{
				type: "square",
				width: 13,
				height:13,
				radius:0,
			},
		},
		sort:{
			by:"#number#",
			dir:"dsc",
			as:"int"
		},
		tooltip:"#name#",
		radius:0,
		border:false,
		yAxis:{
			start:0,
			lines:false,
		}
	});
	barChart.parse(newData,"json");

	toggleChartType('pie');

}


/******* MsgBox *********/
function showMsgBox(){
	var para = {title:'不能查看结果',content:'投票创建者不允许你查看本次投票的结果',noShadow:true,};
	if(checkOpenFrom()){
		para['buttons'] = [{text:'返回', action:'msgBox.hide();history.back();'}]
	}
	msgBox.pop(para);
}
function hideMsgBox(){
	msgBox.hide();
}


